<?php
namespace app\m\controller;
use x\Container;
class User extends Base{

    public function __construct(){
        parent::__construct();
        clear_cookie_arr("js");
        //判断是否登陆
        $this->checkLogin();
    }

    //个人中心
    public function center(){
        return $this->fetch();
    }

    //账户设置
    public function setting(){
        return $this->fetch();
    }

    //基本资料
    public function userEdit(){
        if(is_post()){
            $d = $this->post;
            $rule = [
                'username'=>'require',
                'name'=>'require',
            ];
            $msg = [
                'username.require' => '请输入用户名',
                'name.require' => '请输入真实姓名',
            ];
            check($rule,$msg,$d);
            // if(!empty($d["banknumber"])){
            //     if(strlen($d["banknumber"]) != 16 && strlen($d["banknumber"]) != 19){
            //         err('请填写正确的银行卡卡号!');
            //     }
            // }
            $d['user_id'] = $this->userinfo["id"];
            $re = m('user','c')->saveUser($d);
            if($re){
                cookie('js_url',url('/user/center'));
                cookie('js_msg','保存成功!');
                return suc();
            }else{
                cookie('js_name','code');
                err('保存错误!');
            }
        }
        //用户银行
        $userbank = $this->db->query("select * from user_bank where user_id=?",[$this->userinfo["id"]],1);
        return $this->fetch(['userbank'=>$userbank]);
    }

    //用户手机更改
    public function userPhone(){
        if(is_post()){
            $d = $this->post;
            $rule = [
                'newtel'=>'require',
                'password'=>'require',
                'code'=>'require',
            ];
            $msg = [
                'newtel.require' => '请输入手机号',
                'password.require' => '请输入登陆密码',
                'code.require' => '请输入安证码',
            ];
            check($rule,$msg,$d);
            //短信验证
            if(!m('sms','xcom')->checkCode($d['newtel'], 'newtel', $d['code'])){
                err(m('sms','xcom')->getError());
            }
            $rs = $this->db->query('select id from user where phone=?',[$d['newtel']],1);
            if($rs){
                err('该手机号已存在!');
            }
            $data = [
                "phone" => $d['newtel'],
                "password" => com_password($d['password']),
                "update_time" => time()
            ];
            $result = $this->db->update("user",$data,["id=?",[$this->userinfo["id"]]]);

            if($result){
                cookie('js_url',url('/user/setting'));
                cookie('js_msg','保存成功!');
                return suc();
            }else{
                cookie('js_name','code');
                err('保存错误!');
            }
        }
        return $this->fetch();
    }

    //用户密码
    public function userPwd(){
        if(is_post()){
            $d = $this->post;
            $rule = [
                'oldpassword'=>'require|min:6',
                'newpassword'=>'require|min:6',
                'repassword'=>'require|min:6',
                'code'=>'require',
            ];
            $msg = [
                'oldpassword.require' => '请输入原密码',
                'oldpassword.minlenght' => '密码至少为六位数',
                'newpassword.require' => '请输入新密码',
                'newpassword.minlenght' => '密码至少为六位数',
                'repassword.require' => '请输入确认密码',
                'repassword.minlenght' => '密码至少为六位数',
                'code.require' => '请输入安证码',
            ];
            check($rule,$msg,$d);
            if($d["newpassword"] != $d["repassword"]){
                err('两次密码不一致');
            }
            //短信验证
            if(!m('sms','xcom')->checkCode($this->userinfo["phone"], 'remake', $d['code'])){
                err(m('sms','xcom')->getError());
            }
            $data = [
                "password" => com_password($d['newpassword']),
                "update_time" => time()
            ];
            $re = $this->db->update("user",$data,["id=?",[$this->userinfo["id"]]]);
            if($re){
                cookie('js_url',url('/user/setting'));
                cookie('js_msg','保存成功!');
                return suc();
            }else{
                cookie('js_name','code');
                err('保存错误!');
            }
        }
        return $this->fetch();
    }

    /**
     * 用户购物车
     */
    public function myCart(){
        $goods_model = m("goodsCart", "c");
        $d = $goods_model->getCart($this->userinfo["id"]);
        $cart_list = $d["cart_list"];
        $cart_arr = $d["cart_arr"];
        $cart_total_price = 0;
        $postage_total_price = 0; //总运费
        if($cart_list){
            //购物数据组装
            foreach ($cart_list as $k => $v){
                foreach($cart_arr as $k1 => $v1){
                    if($v["id"] == $v1[0]){
                        if(!isset($cart_list[$k]["postage_total_price"])) $cart_list[$k]["postage_total_price"]=0;
                        $cart_list[$k]["total_price"] = $v1[2]*($v["price"]+$v['postage']);
                        $cart_list[$k]["postage_total_price"] += $v1[2]*$v['postage'];
                        $cart_list[$k]["nums"] = $v1[2];
                    }
                }
            }
            //购物车总价计算
            foreach ($cart_list as $k => $v) {
                $cart_total_price += $v["total_price"];
                $postage_total_price += $v["postage_total_price"];
            }
        }
        //用户地址信息获取
        $map = [];
        $map[] = ["and","user_id","=",$this->userinfo["id"]];
        $w = where($map);
        $address_info = $this->db->query("select * from user_address  $w[0] order by is_default desc",$w[1],1);
        $alist = $this->getAllAddress();
        if($address_info){
            $address_info['address'] = $alist[$address_info['province']] . " " . $alist[$address_info['city']] . " " . $alist[$address_info['district']] . " " . $address_info['address'];
        }
        $this->fetch(['cart_list'=>$cart_list,"cart_total_price"=>$cart_total_price,"cart_count"=>count($cart_list),"address"=>$address_info],'',false);
    }

    //用户地址
    public function userAddr(){
        //收货地址
        $addrlist = $this->db->query('select * from user_address where user_id=? order by id desc',[$this->userinfo["id"]]);
        $alist = $this->getAllAddress();
        $rule = [
            'province' => function($v,$val,$alist){return $alist[$v];},
            'city' => function($v,$val,$alist){return $alist[$v];},
            'district' => function($v,$val,$alist){return $alist[$v];},
        ];
        $addrlist = com_format($addrlist,$rule, $alist);
        return $this->fetch(['addrlist'=>$addrlist]);
    }

    //获取子地区名称
    public function getAllAddress(){
        $rs = $this->db->query('select id,name from com_address');
        $map = [];
        foreach ($rs as $key => $value) {
            $map[$value['id']] = $value['name'];
        }
        return $map;
    }

    //保存收货地址
    public function addAddr(){
        if(is_post()){
            $d = $this->post();
            $rule = [
                'addressname'=>'require',
                'addresstel'=>'require',
                'province'=>'require',
                'city'=>'require',
                'area'=>'require',
                'addressmx'=>'require',
            ];
            $msg = [
                'addressname.require' => '请输入姓名',
                'addresstel.require' => '请输入电话',
                'province.require' => '请选择省',
                'city.require' => '请选择市区',
                'area.require' => '请选择地区',
                'addressmx.require' => '请填写详细地址',
            ];
            check($rule,$msg,$d);
            $default = $this->post("default");
            $data = [
                "user_id" => $this->userinfo["id"],
                "address_name" => $d['addressname'],
                "province" => $d['province'],
                "city" => $d['city'],
                "district" => $d['area'],
                "address" => $d['addressmx'],
                "address_phone" => $d['addresstel'],
                'is_default' => (int)$default,
                "create_time" => time(),
                "update_time" => time()
            ];
            if($default == 1){
                //修改其他默认
                $this->db->update("user_address",['is_default'=>0],["user_id=?",[$this->userinfo["id"]]]);
            }
            $re = $this->db->insert("user_address",$data);
            if($re){
                cookie('js_url',url('/user/userAddr'));
                cookie('js_msg','保存成功!');
                return suc('保存成功!');
            }else{
                cookie('js_name','code');
                err('保存错误!');
            }
        }
        //所有省
        $plist = $this->db->query('select id,name from com_address where parent_id=?',[1]);
        return $this->fetch(['provincelist'=>$plist]);

    }

    //编辑地址
    public function editAddr(){
        if(is_post()){
            $d = $this->post();
            $rule = [
                'addressname'=>'require',
                'addresstel'=>'require',
                'province'=>'require',
                'city'=>'require',
                'area'=>'require',
                'addressmx'=>'require',
            ];
            $msg = [
                'addressname.require' => '请输入姓名',
                'addresstel.require' => '请输入电话',
                'province.require' => '请选择省',
                'city.require' => '请选择市区',
                'area.require' => '请选择地区',
                'addressmx.require' => '请填写详细地址',
            ];
            check($rule,$msg,$d);
            $default = $this->post("default");
            $data = [
                "user_id" => $this->userinfo["id"],
                "address_name" => $d['addressname'],
                "province" => $d['province'],
                "city" => $d['city'],
                "district" => $d['area'],
                "address" => $d['addressmx'],
                "address_phone" => $d['addresstel'],
                'is_default' => (int)$default,
                "create_time" => time(),
                "update_time" => time()
            ];
            if($default == 1){
                //修改其他默认
                $this->db->update("user_address",['is_default'=>0],["user_id=?",[$this->userinfo["id"]]]);
            }
            $rs = $this->db->update("user_address",$data,["id=?",[$d['addressid']]]);
            if($rs){
                cookie('js_url',url('/user/userAddr'));
                cookie('js_msg','保存成功!');
                return suc('保存成功!');
            }else{
                cookie('js_name','code');
                err('保存错误!');
            }
        }
        $id = $this->get("id");
        //所有省
        $plist = $this->db->query('select id,name from com_address where parent_id=?',[1]);
        $ainfo = $this->db->query('select * from user_address where id=? and user_id=?',[$id,$this->userinfo["id"]],1);
        if($ainfo){
            $clist = $this->db->query('select id,name from com_address where parent_id=?',[$ainfo["province"]]);
            $this->assign('citylist',$clist);
            $dlist = $this->db->query('select id,name from com_address where parent_id=?',[$ainfo["city"]]);
            $this->assign('districtlist',$dlist);
        }
        return $this->fetch(['addrinfo'=>$ainfo,'provincelist'=>$plist]);
    }

    //删除地址
    public function delUserAddress(){
        $id = $this->post("id");
        $info = $this->db->query('select * from user_address where id=? and user_id=?',[$id,$this->userinfo["id"]]);
        if($info){
            $re = $this->db->delete('user_address',$id,'id');
            if($re){
                cookie('js_msg','删除成功!');
                return suc('删除成功!');
            }else{
                err('删除失败!');
            }
        }else{
            err('删除失败!');
        }
    }

    //设置默认
    public function defaultAddr(){
        $id = $this->post("id");
        $info = $this->db->query('select * from user_address where id=? and user_id=?',[$id,$this->userinfo["id"]]);
        if($info){
            //修改其他默认
            $this->db->update("user_address",['is_default'=>0],["user_id=?",[$this->userinfo["id"]]]);
            $data = [
                'is_default' => 1
            ];
            $rs = $this->db->update("user_address",$data,["id=?",[$id]]);
            if($rs){
                return suc('设置成功!');
            }else{
                err('设置失败!');
            }
        }else{
            err('设置失败!');
        }
    }

    //删除购物车商品
    public function delCartGoods(){
        $id = $this->post()['id'];
        $goods_model = m("goodsCart", "c");
        $goods_model->deltCart($this->userinfo['id'],$id);
        cookie('js_url',url('/user/myCart'));
        cookie('js_msg','删除成功!');
        suc();
    }


    //获取用户地址信息
    public function getUserAddress(){
        $d = $this->post();
        $id = $d["id"];
        $address_info = $this->db->find("user_address",$id);
        suc($address_info);

    }

    //我的收藏
    public function collect(){
        $d = $this->get();
        $order = 0;
        $page = isset($d['page']) ? (int)$d['page'] : 1;
        if(is_post()){
            $page = $this->post("page");
        }
        $map = [];
        $map[] = ["and","user_id","=",$this->userinfo["id"]];

        $list = m("UserCollect","c")->lists($map,0, $page,5);
        //商品列表推荐位5条数据
        $list = [
            "list"=>$list[0],
            "page_count"=>$list[1],
            'max_page' => ceil($list[1] / 5),
            "page" => $page
        ];
        if(is_post()){
            suc($list);
        }
        $this->fetch($list);
    }

    //添加收藏
    public function goodsCollect(){
        $goodsid = $this->post('goodsid');
        $info = $this->db->query('select * from goods_collect where goods_id=? and user_id=?',[$goodsid,$this->userinfo["id"]]);
        if($info){
            return suc();
        }
        $data = [
            'goods_id' => $goodsid,
            'user_id' => $this->userinfo["id"],
            'create_time' => time(),
        ];
        $re = $this->db->insert('goods_collect',$data);
        if($re){
            return suc();
        }else{
            err('收藏失败!');
        }

    }

    //删除收藏
    public function delCollect(){
        $id = $this->post("id");
        $info = $this->db->query('select * from goods_collect where id=? and user_id=?',[$id,$this->userinfo["id"]]);
        if($info){
            $re = $this->db->delete('goods_collect',$id,'id');
            if($re){
                return suc();
            }else{
                err('删除失败!');
            }
        }else{
            err('删除失败!');
        }
    }

    //交易记录
    public function userBill(){
        $d = $this->get();
        $order = 0;
        $page = isset($d['page']) ? (int)$d['page'] : 1;
        if(is_post()){
            $page = $this->post("page");
        }
        $map = [];
        $map[] = ["and","user_id","=",$this->userinfo["id"]];

        $list = m("UserBill","c")->lists($map,0, $page,20);
        $rule = [
            'type' => function($v){return c("type.user_bill_type.{$v}");},
            'withdraw_status' => function($v){return c("type.withdraw_status.{$v}");},
            'create_time' => 'com_date_format',
        ];
        $billlist = com_format($list[0],$rule);
        $list = [
            "list"=>$billlist,
            "max_page"=>ceil($list[1]/20),
            "page_count"=>$list[1],
            "page" => $page
        ];
        if(is_post()){
            suc($list);
        }
        $this->fetch($list);
    }

    //订单
    public function orderList(){
        $page = $this->get('page',1);
        if(is_post()){
            $page = $this->post('page',2);
        }
        $goodsname = $this->get('goodsname');
        $fahuostatus = $this->get('fahuostatus');
        $d = $this->get();
        $order = 0;

        $map = [];
        if($fahuostatus || $fahuostatus!==''){
            $map[] = ["and","fahuo_status","=",$fahuostatus];
        }
        $map[] = ["and","user_id","=",$this->userinfo["id"]];
        $map[] = ['and',"(order_no like ? or title like ?)",["%{$goodsname}%","%{$goodsname}%"]];
        $w = where($map);
        $rs = $this->db->query("select * from order_goods {$w[0]} order by id desc".limit($page,10), $w[1],'',true);
        if($rs){
          $rule = [
              // 'pay_status' => function($v){return c("type.pay_status.{$v}");},
              'create_time' => 'com_time_format',
          ];
          $data = com_format($rs[0],$rule);
        }

        $list = [
            "goodslist"=>$data,
            "page_count"=>$rs[1],
            "max_page"=>ceil($rs[1]/10),
            "page" => $page,
            'goodsname' => $goodsname,
            'fahuostatus' => $fahuostatus,
        ];
        if(is_post()){
            suc($list);
        }
        $this->fetch($list);
    }

    //商品评价
    public function goodsEvaluate(){
        $id = $this->get('id');
        if($this->post()){
            $d = $this->post();
            $rule = [
                'checked'=>'require',
            ];
            $msg = [
                'checked.require' => '请确认收货后,才能评价',
            ];
            check($rule,$msg,$d);
            $d['user_id'] = $this->userinfo["id"];
            $d['create_time'] = time();
            $d['update_time'] = time();
            unset($d['checked']);
            $this->db->insert('goods_evaluate',$d);
            $data = [
                'id' => $d['order_goods_id'],
                'sh_status' => 1,
            ];
            $this->db->update('order_goods',$data);

            cookie('js_msg','评价成功!');
            cookie('js_function','close|reload');
            suc('评价成功!');
        }
        $order = $this->db->find('order_goods',$id);
        $info  = $this->db->query('select * from goods_evaluate where order_goods_id = ?',[$id],1);
        $this->fetch(['info'=>$info,'order'=>$order]);
    }

    //订单
    public function oldorder(){
        $page = $this->get('page',1);
        if(is_post()){
            $page = $this->post('page',2);
        }
        $d = $this->get();
        $order = 0;
        $map = [];
        $map[] = ["and","khname","=",$this->userinfo["username"]];
        $w = where($map);
        $rs = $this->db->query("select * from buycar {$w[0]} order by time desc".limit($page,10), $w[1],'',true);

        $list = [
            "goodslist"=>$rs[0],
            "page_count"=>$rs[1],
            "max_page"=>ceil($rs[1]/10),
            "page" => $page,
        ];
        if(is_post()){
            suc($list);
        }
        $this->fetch($list);
    }

}
?>
